<template>
	<view>
		<!-- 顶部栏位 -->
		<fui-nav-bar  isFixed isOccupy custom>
			<sn-header :pageUrl="'/pages/cart/index'" @change="shopChange"></sn-header>
			<view v-if="!dropDown" class="u-flex u-row-between" style="position: absolute;right: 35rpx;z-index: 99;">
				<view v-if="!isDel&&list.length!=0" class="u-m-r-30" @click="showDel()">
					<text class="u-font-28">管理</text>
				</view>
				<view v-if="isDel&&list.length!=0" @click="showDel()">
					<fui-tag text="管理" marginRight="20" type="warning" radius="45" theme="plain" size="22"  :border-color="themeColor" :color="themeColor" @close="showDel()" >
						<view class="u-m-l-10">
							<fui-icon name="clear" color="#ffbb1a" :size="26"></fui-icon>
						</view>
					</fui-tag>
				</view>
			</view>
		</fui-nav-bar>
		<view v-if="list.length == 0&&!isFirstLoad" style="text-align: center;margin-top: 200rpx;display: flex;flex-direction: column;align-items: center;">
			<image src="/static/empty/cartEmpty.png" style="width: 428rpx;height:346rpx;margin-bottom: 88rpx;" mode=""></image>
			<text class="u-font-28 grey-color">购物车空空如也，快去逛逛吧~</text>
			<fui-button style="margin-top: 97rpx;width: 200rpx;" @click="$mRouter.switchTab({ route: '/pages/index/index' })">去逛逛</fui-button>
		</view>
		<!-- list区域 -->
		<view v-else class="list">
			<view class="u-m-b-20 u-p-l-35 u-p-r-35 u-p-t-30 box-color" v-for="(item, index) in list" :key="index">
				<fui-checkbox-group>
					<view  class="u-flex u-m-b-30" >
						<fui-checkbox :icon-size="20" :size="40" :checked="item.isSelect" :color="themeColor" @change="checkChildAll(index)">
						</fui-checkbox>
						<text class="u-font-bold u-m-l-20">{{ item.sellerShopName }}</text>
					</view>
				</fui-checkbox-group>
				<fui-checkbox-group 
				@change="checkboxGroupChange">
					<view class="u-flex u-m-b-30" v-for="(item1, index1) in item.shoppingCartItems" :key="index1" >
						<fui-checkbox
							:color="themeColor" 
							class="u-m-r-20"
							@change="checkboxChange(index, index1)"
							:checked="item1.isSelect"
							:name="item1.id"
							:disabled="!isDel&&item1.buyItemReason!=0"
						>
						</fui-checkbox>
						<view class="item"  >
							<view style="flex-basis: 180rpx;position: relative;">
								<image :src="item1.url" style="width: 180rpx;height: 180rpx;border-radius: 10rpx;" mode=""></image>
								<view class="not-buy u-flex u-row-center" v-if="item1.buyItemReason!==0">
									<view class="not-buy-reason"> {{item1.buyItemReasonString}} </view>
								</view>
							</view>
							<view style="flex: 1; margin-left: 20rpx;overflow: hidden;">
								<view class="u-flex u-row-between u-m-b-16">
									<view class="u-font-28 u-line-1 " style="flex: 1;">{{ item1.itemName }}</view>
									<fui-icon name="delete" size="40" color="#333" @tap="delItemOneTap(item1.id,index1,index)"></fui-icon>
								</view>
								<view class="u-flex u-row-between">
									<view class="grey-box">
										{{ item1.specification }}
									</view>
									<text class="badge-color u-font-32">￥{{ item1.price }}<text class="u-font-24">/{{item1.unit||'瓶'}}</text></text>
								</view>
								<view class="u-flex u-row-between u-m-t-10" >
									<text class="info-color u-font-22">销售单位{{ item1.sellingUnit }}{{item1.unit}}</text>
									<!-- 修改数量 -->
									<number-box 
									v-if="item1.buyItemReason<2"
									:noBalance="item1.inventoryBalance<item1.sellingUnit"
									 boxWidth="100rpx" width="200rpx" height="50rpx" fontSize="28rpx"
									 :value="item1.quantity" :step="item1.sellingUnit?item1.sellingUnit:1" 
									:min="item1.sellingUnit?item1.sellingUnit:1" 
									@change="updateQuantity($event, index, index1,item1.inventoryBalance,item1.sellingUnit)"></number-box>
								</view>
							</view>
						</view>
					</view>
				</fui-checkbox-group>
				<view v-if="!isDel && item.isShowJs">
					<sn-line color="#000000" style="opacity: 0.1;" />
					<view class="box-color u-flex u-row-between" style="height: 100rpx;">
						<view v-if="item.total < item.baseValue" class="u-flex">
							<image src="/static/common/yanzheng_small.png" style="width: 30rpx;height:30rpx;" mode=""></image>
							<view class="u-flex-col u-m-l-20">
								<text class="u-font-22 badge-color">起购金额</text>
								<text class="u-font-22 badge-color">￥ {{ item.baseValue }}</text>
							</view>
						</view>
						<view v-else></view>
						<view class="u-flex">
							<text class="u-font-28">合计：</text><text class="badge-color u-font-32">￥{{ item.total }}</text>
							<view class="u-m-l-30">
								<fui-button v-if="item.total >= item.baseValue"  width="160rpx" height="70rpx" size="28" @click="toSettlement(index)">结算</fui-button>
								<fui-button v-else hover-class="none" shape="circle" :ripple="true" :hair-line="false" :style="{ backgroundColor: '#BBBBBB', width: '160rpx', height: '70rpx', fontSize: '26rpx', border: 0 }">结算</fui-button>
							</view>
						</view>
					</view>
				</view>
			</view>
		</view>
		<!-- 删除时底部显示 -->
		<view v-if="isDel&&list.length!=0" class="footer u-flex u-row-between u-p-l-35 u-p-r-35" :style="{bottom: delBottom}">
			<view class="u-flex">
				<fui-checkbox :icon-size="20" :size="40" :checked="allChecked" :color="themeColor" @change="deleteAll">
				</fui-checkbox>
				<text class="u-m-l-10">全选</text>
			</view>
			
			<view class="u-m-l-30">
				<fui-button :style="getBtStyle('default', 200, 80, 28)"  width="160rpx" height="70rpx" size="28" @click="beforeDelete">删除</fui-button>
			</view>
		</view>
		<!-- 是否删除弹窗 -->
		<!-- <u-modal v-model="modalShow" :show-title="false" content="是否确认删除" @confirm="handleDelete" :show-cancel-button="true"></u-modal> -->
		<!--页面加载动画-->
		<fui-tabbar  :isFixed="true" ></fui-tabbar>
		<!-- <akLoading isFullScreen :active="loading"></akLoading> -->
		<!-- <u-no-network></u-no-network>
		<u-popup v-model="addEmptyShow" class="empty-container" mode="center" :mask-close-able="false"	>
			<view >
				<view class="empty-content">
					<view class="empty-bg" >
						<view class="u-font-32" >贵公司未配置</view>
						<view class="empty-top-text"  style="">收货地址</view>
						<view class="empty-bot-btn" v-if="storeShop.managerId == $store.state.user.user.id" @click="$mRouter.push({route: '/pages/purchase/shezhi/dizhi?shopId='+storeShop.id})">立即配置</view>
						<view class="empty-bot-text" v-else>
							<view class="u-text-center u-font-32">请联系管理员配置</view>
							<view class="u-text-center u-font-32">收货地址</view>
						</view>
					</view>
				</view>
				<view class="empty-close" @click="addEmptyShow = false"></view>
			</view>
			
		</u-popup>
		<u-action-sheet  :list="delItemOption" @click="delItemOneFn" safe-area-inset-bottom	 v-model="delItemShow"></u-action-sheet> -->
	</view>
</template>

<script>
	import NumberBox from '@/components/number-box.vue';
	import SnLine from '@/components/sn-line.vue';
	import {useShopStore} from '@/store/shop.js';
	import {useCartStore} from '@/store/cart.js';
	import { mapState } from 'pinia';
	export default {
		components: { NumberBox,SnLine },
		data() {
			return {
				addEmptyShow:false,
				loading: false,
				modalShow: false,
				isDel: false,
				allChecked: false,
				dropDown: false,
				list: [],
				selectedList: [],
				// #ifndef H5
				delBottom: uni.getSystemInfoSync().platform == 'ios' ? '170rpx' : '120rpx',
				// #endif
				// #ifdef H5
				delBottom: '120rpx',
				// #endif
				delOneId:'',
				delOneIndex:0,
				delOneListIndex:0,
				delItemShow:false,
				delItemOption:[
					{
						text: '删除',
						color: '#ff551a',
						fontSize: 32,
						
					}
				],
				isFirstLoad:true
			}
		},
		
		// async onLoad() {
		// 	await this.$onLaunched;
		// },
		async onShow() {
			if (!this.storeShop.id) {
				return
			}
			// 获取购物车列表
			this.getCartList()
			this.isDel = false;
		},
		computed:{
			...mapState(useShopStore, {
				  storeShop: 'shop'}),
			...mapState(useCartStore, ['setSettlementInfo']),
			
		},
		onReady() {
		},
		methods: {
			shopChange(){
				console.log('切换店铺');
				this.getCartList()
				this.isDel = false;
			},
			delItemOneTap(id,index,dadIndex){
				this.delOneId = id;
				this.delOneIndex = index;
				this.delOneListIndex = dadIndex;
				this.delItemShow = true;
			},
			async delItemOneFn(){
				this.loading = true;
				let ary = [];
				ary.push(this.delOneId);
				const res = await this.$newHttp.delete('api/ShoppingCart/DeleteShoppingCart', ary);
				this.loading = false;
				if(res.code === 200){
					uni.$fui.toast('删除商品成功');
					// this.getCartList()
					if(this.list[this.delOneListIndex].shoppingCartItems.length ===1){
						this.list.splice(this.delOneListIndex,1);
					}else{
						this.list[this.delOneListIndex].shoppingCartItems.splice(this.delOneIndex,1);
						this.sumTotal(this.delOneListIndex)
					}
				}else{
					uni.$fui.toast('删除商品失败，错误信息：'+res.erroMessage);
				}
				// 刷新数据
			},
			// 获取购物车列表
			async getCartList() {
				this.loading = true;
				let params = {
					PageIndex: 1,
					PageSize: 10,
					shopId:this.storeShop.id
				}
				const res = await this.$newHttp.get('api/ShoppingCart/GetShoppingCarts', { params: params });
				this.loading = false;
				this.isFirstLoad = false; //第一次加载
				if(res.code === 200){
					this.list = res.data;
				}else{
					uni.$fui.toast('获取购物车信息失败，错误信息：'+res.erroMessage);
				}
			},
			// 修改数量
			async updateQuantity(v, i, i1,inv) {
				uni.showLoading()
				// 请求接口
				const params = {
					id: this.list[i].shoppingCartItems[i1].id,
					quantity: v
				}
				const res = await this.$http.put('api/ShoppingCart/UpdateShoppingCart', params)
				uni.hideLoading()
				this.list[i].shoppingCartItems[i1].quantity = v;
				// this.list[i].shoppingCartItems[i1].selectable = res.selectable;
				this.list[i].shoppingCartItems[i1].buyItemReason = res.buyItemReason;
				this.list[i].shoppingCartItems[i1].buyItemReasonString = res.buyItemReasonString;
				// if(!this.isDel&&!res.selectable){
				if(!this.isDel&&res.buyItemReason!=0){
					this.list[i].shoppingCartItems[i1].isSelect = false;
				}
				// 如果是勾选中 则需要计算金额
				if (this.list[i].shoppingCartItems[i1].isSelect) {
					this.sumTotal(i)
				}
			},
			// 勾选店铺复选框
			checkChildAll(index) {
				const bool = !this.list[index].isSelect
				this.list[index].isSelect = bool
				// 结算按钮
				this.list[index].isShowJs = bool
				// 如果是删除状态 判断全选是否需要勾选
				this.checkDeleteAll()
				let total = 0
				for (let i = 0; i < this.list[index].shoppingCartItems.length; i++) {
					if(this.isDel){
						this.list[index].shoppingCartItems[i].isSelect = bool
						this.changeSelectedList(this.list[index].shoppingCartItems[i].id, bool)
						if (bool) total = this.addFn(total,this.mulFn(this.list[index].shoppingCartItems[i].price,this.list[index].shoppingCartItems[i].quantity))
					}else{
						// if(this.list[index].shoppingCartItems[i].selectable){
						if(this.list[index].shoppingCartItems[i].buyItemReason === 0){
							this.list[index].shoppingCartItems[i].isSelect = bool
							this.changeSelectedList(this.list[index].shoppingCartItems[i].id, bool)
							if (bool) total = this.addFn(total,this.mulFn(this.list[index].shoppingCartItems[i].price,this.list[index].shoppingCartItems[i].quantity))
						}
					}
					
				}
				this.list[index].total = total;
			},
			// 选中某个复选框时，由checkbox时触发
			checkboxChange(parentIndex, index) {
				const current = this.list[parentIndex].shoppingCartItems
				current[index].isSelect = !current[index].isSelect
				this.changeSelectedList(current[index].id, current[index].isSelect)
				// 计算金额
				this.sumTotal(parentIndex)
				// 如果勾选为true 那么就显示结算按钮 并且判断店铺是否勾选
				if (current[index].isSelect) {
					
					this.list[parentIndex].isShowJs = true
					// 只要有一个未勾选 店铺就不勾选
					const res = current.every((value, index) => {
						return value.isSelect == true
					})
					this.list[parentIndex].isSelect = res
					// 如果是删除状态 判断全选是否需要勾选
					this.checkDeleteAll()
				} else {
					this.list[parentIndex].isSelect = false
					// 只要有一个勾选 就显示结算按钮
					const res = current.some((value, index) => {
						return value.isSelect == true
					})
					this.list[parentIndex].isShowJs = res
					// 只要一个子集未勾选 全部删除就未勾选
					this.allChecked = false
				}
			},
			// 改变选中数组
			changeSelectedList(id, bool) {
				if (bool) {
					this.selectedList.push(id)
				} else {
					const index = this.selectedList.findIndex(item => {
						return item == id
					})
					this.selectedList.splice(index, 1)
				}
				// console.log(this.selectedList)
			},
			// 选中任一checkbox时，由checkbox-group触发
			checkboxGroupChange(e) {
				// console.log(e);
			},
			// 显示删除
			showDel() {
				this.isDel = !this.isDel;
				// 判断第一次进来删除全选是否勾选
				this.checkDeleteAll()
			},
			// 删除全选是否勾选
			checkDeleteAll() {
				if (!this.isDel) return;
				const allDel = this.list.every(val => {
					return val.isSelect == true
				})
				this.allChecked = allDel
			},
			// 删除全选
			deleteAll() {
				this.list.forEach((value, index) => {
					// val.isSelect = true;
					this.checkChildAll(index)
				})
			},
			// 计算合计金额
			sumTotal(index) {
				// 如果是在删除状态就不计算
				if (this.isDel) return;
				let total = 0
				for (let i = 0; i < this.list[index].shoppingCartItems.length; i++) {
					if (!this.list[index].shoppingCartItems[i].isSelect) continue;
					// total += this.list[index].shoppingCartItems[i].price * this.list[index].shoppingCartItems[i].quantity
					total = this.addFn(total,this.mulFn(this.list[index].shoppingCartItems[i].price,this.list[index].shoppingCartItems[i].quantity));
				}
				this.list[index].total = total;
			},
			// 删除前判断
			beforeDelete() {
				if (this.selectedList.length == 0) {
					return uni.$fui.toast('您还没有选择商品')
				}
				this.modalShow = true
			},
			// 删除接口
			async handleDelete() {
				// 如果购物车为空 无法调用删除接口
				if (this.selectedList.length == 0) return
				const res = await this.$http.delete('api/ShoppingCart/DeleteShoppingCart', this.selectedList)
				this.selectedList = []
				// 刷新数据
				this.getCartList()
			},
			toSettlement(index){
				if(this.storeShop.deliveryAddresses.length === 0){
					this.addEmptyShow = true;
				}else{
					this.toPage(index)
				}
			},
			toPage(index) {
				let info = Object.assign({}, this.list[index])
				const list = info.shoppingCartItems.filter(item => {
					return item.isSelect&&item.buyItemReason===0
				})
				if(list.length === 0){
					uni.$fui.toast('勾选商品为空，请勾选后提交');
					return false;
				};
				info.shoppingCartItems = list;
				this.setSettlementInfo(info);
				this.$mRouter.push({ route: '/pages/cart/jiesuan' });
			},
			mulFn(a,b){
			  return this.$mHelper.mul(a,b)
			},
			addFn(a,b){
			  return this.$mHelper.add(a,b)
			},
			subFn(a,b){
			  return this.$mHelper.sub(a,b)
			},
			devFn(a,b){
			  return this.$mHelper.dev(a,b)
			},
		}
	}
</script>
 
<style lang="scss" scoped>
	.empty-container{
		::v-deep .u-mode-center-box{
			background-color: transparent !important;
		}
		.empty-content{
			box-sizing: border-box;
			padding-left: 50rpx;
			.empty-bg{
				background: url('/static/order/tanchuangbg.png') no-repeat;
				width: 541rpx;
				height: 478rpx;
				background-size: 100% 100%;
				box-sizing: border-box;
				padding: 70rpx 44rpx;
				.empty-top-text{
					font-weight: bold;
					font-size: 48rpx;
					margin-top: 10rpx;
				}
				.empty-bot-btn{
					width: 252rpx;
						text-align: center;
						line-height: 90rpx;
						font-size: 32rpx;
						margin: 140rpx 0 0rpx 80rpx;
						height: 90rpx;
						background: #FFBB1A;
						box-shadow: 0px 8px 15px 3px rgba(255,187,26,0.2400);
						border-radius: 45rpx;
				}
				.empty-bot-text{
					margin: 140rpx 0 0rpx 80rpx;
					width: 252rpx;
				}
			}
		}
		.empty-close{
			background: url('/static/order/closebg.png') no-repeat;
			background-size: 100% 100%;
			width: 62rpx;
			height: 62rpx;
			margin: 60rpx auto;
		}
		
	}
	
	.list {
		margin-bottom: 150rpx;
		.item {
			display: flex;
			height: 180rpx;
			flex:1;overflow: hidden;
			box-sizing: border-box;
			image {
				border-radius: 10rpx;
			}
			.not-buy{
				position: absolute;
				left: 0;
				top: 0;
				width: 180rpx;
				height: 180rpx;
				background-color: rgba(255, 255, 255, 0.6);
				.not-buy-reason{
					background: rgba(0,0,0,0.45);
					color: #DEDEDE;
					border-radius:25rpx;
					box-sizing: border-box;
					padding: 6rpx 20rpx;
					font-size: 24rpx;
				}
			}
			.grey-box {
				padding: 0 15rpx;
				background: #F8F8F8;
				border-radius: 5rpx;
				font-size: 22rpx;
				color:#999999;
				text-align: center;
			}
		}
	}
	.footer {
		position: fixed;
		bottom: 100rpx;
		z-index: 99;
		width: 100%;
		height: 100rpx;
		background-color: #FFFFFF;
	}
	::v-deep {
		.u-close-icon {
			margin-left: 5rpx;
		}
	}
	::v-deep .u-checkbox__label {
		margin-left: 20rpx;
		width: 100%;
		margin-right: 0;
	}
	::v-deep .u-dropdown__menu__item__text {
		font-weight: bold;
	}
</style>
